<template>
  <a-card style="z-index: 1">
    <!--    质检状态-->
    <div>
      <a-divider></a-divider>
      <h1><b>质检状态</b></h1>
      <div style="padding-left: 24px">
        <a-radio-group v-memo="[formData.status]" v-model:value="formData.status" @change="formData.resultBak=[]">
          <a-radio v-for="item in checkStatusOptions" :key="item" :value="item.value">{{ item.label }}</a-radio>
        </a-radio-group>
      </div>
      <div v-if="formData.status===1" style="padding-left: 24px;margin-top: 8px">
        质检中断原因：
        <a-checkbox-group v-memo="formData.resultBak" v-model:value="formData.resultBak">
          <a-checkbox value="有屏幕锁">有屏幕锁</a-checkbox>
          <a-checkbox value="账号未退出">账号未退出</a-checkbox>
        </a-checkbox-group>
      </div>
    </div>

    <!--    基础信息-->
    <div>
      <a-divider></a-divider>
      <h1><b>质检状态</b></h1>
      <div style="padding-left: 8px">
        <div class="row">
          <div class="label">型号：</div>
          <div class="rowContent">
            <a-select
                v-model:value="formData.modelId"
                :default-active-first-option="false"
                :disabled="formDataNoneItem.modelIdNoneItem"
                :field-names="{ label: 'modelName', value: 'id' }"
                :filter-option="false"
                :not-found-content="null"
                :options="modelOptions"
                :show-arrow="false"
                allow-clear
                placeholder="请输入型号并选择"
                show-search
                style="width: 300px"
                @change="modelChange"
                @search="modelSearch"
            ></a-select>
            <a-button :type="formDataNoneItem.modelIdNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('modelId','modelIdNoneItem')">
              {{ formDataNoneItem.modelIdNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>
        <div class="row">
          <div class="label">存储容量：</div>
          <div class="rowContent">
            <a-radio-group v-if="formData.modelId" v-memo="[formData.storage]" v-model:value="formData.storage">
              <a-radio v-for="memory in memoryOptions" :key="memory" :disabled="formDataNoneItem.storageNoneItem"
                       :value="memory">{{ memory }}
              </a-radio>
            </a-radio-group>
            <span v-else style="color: #999999">请先选择机型</span>
            <a-button :type="formDataNoneItem.storageNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('storage','storageNoneItem')">
              {{ formDataNoneItem.storageNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>
        <div class="row">
          <div class="label">颜色：</div>
          <div class="rowContent">
            <a-radio-group v-if="formData.modelId" v-memo="[formData.color]" v-model:value="formData.color">
              <a-radio v-for="color in colorOptions" :key="color" :disabled="formDataNoneItem.colorNoneItem"
                       :value="color">{{ color }}
              </a-radio>
            </a-radio-group>
            <span v-else style="color: #999999">请先选择机型</span>
            <a-button :type="formDataNoneItem.colorNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('color','colorNoneItem')">
              {{ formDataNoneItem.colorNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>
        <div class="row">
          <div class="label">购买渠道：</div>
          <div class="rowContent">
            <div>
              <template v-for="item in deviceSourceOptions" :key="item" v-memo="[formData.phoneType]">
                <a-radio :checked="formData.phoneType==item.value" :disabled="formDataNoneItem.phoneTypeNoneItem"
                         :value="item.value"
                         @click="formData.phoneType=item.value">
                  {{ item.label }}
                </a-radio>
                <span v-once :data-title="item.tips" class="infoIcon">i</span>
              </template>
            </div>
            <a-button :type="formDataNoneItem.phoneTypeNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('phoneType','phoneTypeNoneItem')">
              {{ formDataNoneItem.phoneTypeNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>
        <div class="row">
          <div class="label">网络制式：</div>
          <div class="rowContent">
            <div>
              <template v-for="item in networkTypeOptions" :key="item" v-memo="[formData.network]">
                <a-radio :checked="formData.network==item.value" :disabled="formDataNoneItem.networkNoneItem"
                         :value="item.value"
                         @click="formData.network=item.value">
                  {{ item.label }}
                </a-radio>
                <span v-once :data-title="item.tips" class="infoIcon">i</span>
              </template>
            </div>
            <a-button :type="formDataNoneItem.networkNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('network','networkNoneItem')">
              {{ formDataNoneItem.networkNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>
        <div class="row">
          <div class="label">序列号：</div>
          <div class="rowContent">
            <div>
              <a-input v-model:value="formData.serialNumber" :disabled="formDataNoneItem.serialNumberNoneItem"
                       placeholder="请输入序列号" style="width: 300px"/>
              <span v-once data-title="魅族机型：设置-关于本机-状态信息-查看序列号" class="infoIcon" style="margin-left: 8px">i</span>
            </div>
            <a-button :type="formDataNoneItem.serialNumberNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('serialNumber','serialNumberNoneItem')">
              {{ formDataNoneItem.serialNumberNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>
        <div class="row">
          <div class="label">IMEI：</div>
          <div class="rowContent">
            <div>
              <a-input v-model:value="formData.imei" :disabled="formDataNoneItem.imeiNoneItem"
                       placeholder="请输入IMEI" style="width: 300px"/>
              <span v-once :data-title="'1、拔号APP输入“#06#“查看IMEI 2、如该设备IMEI号异常无显示填写N/A 3、无IMEI，仅有MEID的填写MEID 4、小米平板录入PSN，苹果手表SN，都录大写'" class="infoIcon" style="margin-left: 8px">i</span>
            </div>
            <a-button :type="formDataNoneItem.imeiNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('imei','imeiNoneItem')">
              {{ formDataNoneItem.imeiNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>
        <div class="row">
          <div class="label">电池健康值：</div>
          <div class="rowContent">
            <div>
              <template v-for="item in batteryOptions" :key="item" v-memo="[formData.batteryHealth]">
                <a-radio :checked="formData.batteryHealth==item.value"
                         :disabled="formDataNoneItem.batteryHealthNoneItem" :value="item.value"
                         @click="formData.batteryHealth=item.value">
                  {{ item.label }}
                </a-radio>
                <span v-if="item.tips" v-once :data-title="item.tips" class="infoIcon">i</span>
              </template>
            </div>
            <a-button :type="formDataNoneItem.batteryHealthNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('batteryHealth','batteryHealthNoneItem')">
              {{ formDataNoneItem.batteryHealthNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>
        <div class="row">
          <div class="label">充电次数：</div>
          <div class="rowContent">
            <a-input-number v-model:value="formData.chargeCount" :disabled="formDataNoneItem.chargeCountNoneItem"
                            addon-after="次" placeholder="请输入充电次数"
                            style="width: 180px"></a-input-number>
            <a-button :type="formDataNoneItem.chargeCountNoneItem?'danger':'primary'"
                      ghost @click="changeBaseNoneItem('chargeCount','chargeCountNoneItem')">
              {{ formDataNoneItem.chargeCountNoneItem ? '无此项' : '有此项' }}
            </a-button>
          </div>
        </div>


      </div>
    </div>


    <div v-for="(model,templateIndex) in templateList" :key="model">
      <a-divider></a-divider>
      <h1><b>{{ model.title }}</b></h1>
      <div style="padding-left: 8px">
        <div v-for="(rowData,index) in model.children" :key="rowData" class="row">
          <div class="label">{{ rowData.subject }}：</div>
          <div class="rowContent">
            <div v-if="rowData.optionType===1" style="max-width: 800px">
              <template v-for="item in rowData.options" :key="item">
                <a-radio :checked="rowData.radioSelected==item.value" :disabled="rowData.noneItem" :value="item.value"
                         @change="singleChange(rowData,$event)">
                  {{ item.label }}
                </a-radio>
                <span v-once :data-title="item.tips" class="infoIcon">i</span>
              </template>
            </div>

            <div v-if="rowData.optionType===2" style="max-width: 800px">
              <a-checkbox-group :value="rowData.checkedSelected" @change="multipleChange(rowData,$event)">
                <a-row>
                  <a-col v-for="m in rowData.options" :key="m">
                    <a-checkbox :disabled="rowData.noneItem" :value="m.value">
                      {{ m.label }}
                    </a-checkbox>
                    <span v-once :data-title="m.tips" class="infoIcon">i</span>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </div>

            <div style="display: flex;align-items: center">
              <span v-if="!rowData.noneItem"
                    style="color: #40a9ff;width: 60px;display: inline-block;text-align: center;white-space: nowrap;margin-right: 8px;cursor: pointer"
                    @click="showRowDataImg(templateIndex,index)">图片说明</span>
              <span v-else
                    style="color: rgba(0, 0, 0, 0.25);width: 60px;display: inline-block;text-align: center;white-space: nowrap;margin-right: 8px;cursor: pointer"
              >图片说明</span>
              <a-button :type="rowData.noneItem?'danger':'primary'" ghost @click="itemNoneItem(rowData)">
                {{ rowData.noneItem ? '无此项' : '有此项' }}
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--    验机图片-->
    <div>
      <a-divider></a-divider>
      <h1><b>验机图片</b></h1>
      <div>
        <FileUpload
            :multiple-select="true"
            v-memo="formData.imgs"
            :defaultFileList="formData.imgs"
            :folder="FILE_FOLDER_TYPE_ENUM.CHECKDEVICE.value"
            :maxUploadSize="20"
            :multiple="true"
            buttonText="点击上传图片"
            list-type="picture-card"
            @change="checkDeviceImgChange"
        />
      </div>
    </div>
    <!--    质检结果-->
    <div>
      <a-divider></a-divider>
      <div v-memo="[formData.price]" class="row">
        <div class="label" style="align-self: flex-start">质检价格：</div>
        <div>
          <a-input-number v-model:value="formData.price" addon-after="元" placeholder="请输入质检价格"
                          style="width: 180px"></a-input-number>
          <a-button type="link" @click="showCheckTemplateModal">估价参考</a-button>
        </div>
      </div>

      <div v-memo="[formData.checkNote]" class="row">
        <div class="label" style="align-self: flex-start">质检备注：</div>
        <div>
          <a-textarea v-model:value="formData.checkNote" :maxlength="200" placeholder="仅供客服查看"
                      show-count
                      style="width: 400px"/>
        </div>
      </div>
      <div v-memo="[formData.checkExplain]" class="row">
        <div class="label" style="align-self: flex-start">质检说明：</div>
        <div>
          <a-textarea v-model:value="formData.checkExplain" :maxlength="200" placeholder="供用户查看"
                      show-count
                      style="width: 400px"/>
          <div style="color: red">注意：供用户查看，请注意措辞</div>
        </div>
      </div>
      <div v-memo="[formData.storageId,...warehouseOptions]" class="row">
        <div class="label">仓储区：</div>
        <div>
          <a-select v-model:value="formData.storageId" :field-names="{label: 'storageName',value: 'id'}"
                    :options="warehouseOptions"
                    allowClear
                    placeholder="选择仓储区" style="width: 160px" @change="storageAreaChange">
          </a-select>
        </div>
      </div>
      <div v-memo="[formData.storageRackId,...goodsShelfOptions]" class="row">
        <div class="label">货架：</div>
        <div>
          <a-select v-model:value="formData.storageRackId"
                    :field-names="{label: 'rackName',value: 'id'}"
                    :options="goodsShelfOptions"
                    allowClear placeholder="选择货架" style="width: 160px">
          </a-select>
        </div>
      </div>
      <div class="row" style="margin: 48px 0;padding-left: 208px">
        <a-button v-once style="margin-right: 24px" @click="cancel">取消</a-button>
        <a-button v-once type="primary" @click="save">保存</a-button>
        <a-checkbox v-model:checked="printRequire" style="margin-left: 8px">打印机器标签</a-checkbox>
      </div>

    </div>

  </a-card>


  <!--  图片说明对话框-->
  <a-modal :footer="null" :title="'图片说明-'+aboutImgDialog.title"
           :visible="aboutImgDialog.visible"
           width="100%" @cancel="hideAboutImgDialog">
    <a-tabs type="card">
      <a-tab-pane key="imgs" tab="已添加图片">
        <a-row>
          <a-col
              v-for="(item,imgIndex) in templateList[aboutImgDialog.templateIndex]?.children[aboutImgDialog.rowDataIndex]?.imgLists"
              :key="item"
              style="margin: 8px 24px;border: 1px dashed #999999;position: relative">
            <DeleteOutlined
                style="position: absolute;top: 0;right: 0;z-index: 9999;color: red;font-size: 28px;cursor: pointer"
                @click="removeAboutImg(imgIndex)"/>
            <a-image
                style="width: 200px;height: 200px"
                :height="200"
                :src="item"
                :width="200"
            />
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane key="addImg" tab="添加图片">
        <div>
          <h3><b>从验机图片中选择</b></h3>
          <a-row>
            <a-col v-for="item in aboutImgDialog.checkDeviceImgs"
                   :key="item" style="margin: 8px 24px;text-align: center">
              <a-image
                  style="width: 102px;height: 102px"
                  :height="102"
                  :src="item.url"
                  :width="102"
              />
              <div>
                <a-checkbox v-model:checked="item.checked" style="margin-top: 8px"></a-checkbox>
              </div>
            </a-col>
          </a-row>
          <h3><b>从电脑中选择</b></h3>
          <FileUpload
              :multiple-select="true"
              :defaultFileList="aboutImgDialog.uploadedImgs"
              :folder="FILE_FOLDER_TYPE_ENUM.CHECKDEVICE.value"
              :maxUploadSize="5"
              :multiple="true"
              buttonText="点击上传图片"
              list-type="picture-card"
              @change="aboutImgChange"
          />
        </div>
        <div style="text-align: right">
          <a-button type="primary" @click="addAboutImg">添加</a-button>
        </div>
      </a-tab-pane>
    </a-tabs>

  </a-modal>

  <check-template ref="checkTemplateRef" :model-id="formData.modelId" :order-detail="orderDetail"
                  :order-id="orderId"></check-template>
  <printer ref="printerRef"></printer>
</template>

<script setup>
import {useRoute} from "vue-router";
import {onMounted, reactive, ref} from "vue";
import {orderApi} from "/@/views/business/order/order";
import {modelApi} from "/@/views/business/data-config/model/model-api";
import {FILE_FOLDER_TYPE_ENUM} from "/@/constants/support/file-const";
import FileUpload from "/@/components/support/file-upload/index.vue";
import {message} from "ant-design-vue";
import {useUserStore} from "/@/store/modules/system/user";
import CheckTemplate from "/@/views/business/order/checkTemplate.vue";
import {storageAreaApi} from "/@/views/business/storage/storage-area";
import {storageRackApi} from "/@/views/business/storage/storage-rack";
import Printer from "/@/views/business/printer/printer.vue";

const checkTemplateRef = ref();
const printerRef = ref();

const printRequire = ref(false);

const orderId = ref('');
const deviceId = ref('');
const route = useRoute();
const templateList = ref([]);//模版列表
const modelOptions = ref([]);//机型选项
const memoryOptions = ref([]);//内存选项
const colorOptions = ref([]);//颜色选项
const warehouseOptions = ref([]);//仓储区选项
const goodsShelfOptions = ref([]);//货架号选项
// 质检状态
const checkStatusOptions = ref([
  {label: '质检中断', value: 1},
  {label: '质检完成', value: 2},
  {label: '待继续验机', value: 3},
  {label: '无法质检', value: 4},
]);
// 设备来源
const deviceSourceOptions = ref([
  {label: '国行', value: '国行', tips: `③三星S10以上机器，设置-关于手机-软件信息-运营商软件版本-最下面一行全为CHC`},
  {
    label: '港澳台',
    value: '港澳台',
    tips: `①苹果设备：关于本机及软件查询为ZP/A11代以上为ZA/ZP/TA ②苹果SE1代： MO/A澳门版`
  },
  {label: '其他版本', value: '其他版本', tips: '中国以外的版本'},
  {label: '其他版本-有锁', value: '其他版本-有锁', tips: 'IMEI'},
]);
// 网络制式
const networkTypeOptions = ref([
  {
    label: '全网通', value: '全网通', tips: '针对安卓机型：\n' +
        '①有系统映射的按照系统映射就好\n' +
        '②查看网络制式表\n' +
        '③国行默认5G，国内品牌其它版本以及（港澳台版本）默认实测，外国品牌其它版本默认4G\n' +
        '④网络制式表里没有的实测'
  },
  {
    label: '双网通', value: '双网通', tips: '针对安卓机型：\n' +
        '①有系统映射的按照系统映射就好\n' +
        '②查看网络制式表\n' +
        '③国行默认5G，国内品牌其它版本以及（港澳台版本）默认实测，外国品牌其它版本默认4G\n' +
        '④网络制式表里没有的实测'
  },
  {
    label: '移动版', value: '移动版', tips: '针对安卓机型：\n' +
        '①有系统映射的按照系统映射就好\n' +
        '②查看网络制式表\n' +
        '③国行默认5G，国内品牌其它版本以及（港澳台版本）默认实测，外国品牌其它版本默认4G\n' +
        '④网络制式表里没有的实测'
  },
  {label: '联通版', value: '联通版', tips: 'IMEI'},
  {label: '电信版', value: '电信版', tips: 'IMEI'},
]);
const batteryOptions = ref([
  {label: '>=95%', value: '>=95%', tips: ''},
  {label: '90%-95%', value: '90%-95%', tips: ''},
  {label: '85%-90%', value: '85%-90%', tips: ''},
  {label: '80%-85%', value: '80%-85%', tips: ''},
  {label: '<80%', value: '<80%', tips: ''},
])
const formDataNoneItem = reactive({
  modelIdNoneItem: false,
  storageNoneItem: false,
  colorNoneItem: false,
  phoneTypeNoneItem: false,
  networkNoneItem: false,
  serialNumberNoneItem: false,
  imeiNoneItem: false,
  batteryHealthNoneItem: false,
  chargeCountNoneItem: false,
})
const formData = reactive({
  status: 1,// 质检状态
  resultBak: [],// 质检中断原因
  modelId: undefined,// 型号
  storage: undefined,// 存储容量
  color: undefined,// 颜色
  phoneType: undefined,// 购买渠道
  network: undefined,// 网络制式
  serialNumber: undefined,// 序列号
  imei: undefined,// IMEI
  batteryHealth: undefined,// 电池健康
  chargeCount: undefined,// 充电次数
  checkContext: [],// 验机报告
  imgs: [],// 验机图片
  price: 0,// 质检价格
  checkNote: undefined,// 质检备注
  checkExplain: undefined,// 验机说明
  storageId: undefined,// 仓储区
  storageRackId: undefined,// 货架
});
// 模版选项图片说明对话框
const aboutImgDialog = reactive({
  visible: false,
  title: undefined,
  templateIndex: undefined,// 模版index
  rowDataIndex: undefined,// 选项index
  checkDeviceImgs: [],// 当前已有验机图片
  uploadedImgs: [],//上传的图片
})

const orderDetail = reactive({});

onMounted(async () => {
  orderId.value = route.query.orderId;
  deviceId.value = route.query.id;
  orderApi.detail(orderId.value).then(res => {
    Object.assign(orderDetail, res.data)
  })
  storageAreaApi.queryPage({
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    warehouseOptions.value = res.data.list;
    console.log(warehouseOptions.value)
  });
  await orderApi.getCheckModel().then(res => {
    templateList.value = res.data;
  });
  if (route.query.id) {
    await orderApi.getCheckDeviceDetail(deviceId.value).then(res => {
      Object.assign(formData, {
        ...res.data,
        imgs: JSON.parse(res.data.imgs),
        resultBak: JSON.parse(res.data.resultBak),
      });
      templateList.value = JSON.parse(res.data.checkContext);
      Object.assign(formDataNoneItem, JSON.parse(res.data.noSuchFlag));
      console.log(res.data)
    });
    let responseModel = await modelApi.queryPage({
      modelId: formData.modelId, //型号id
      pageNum: 1,
      pageSize: 50,
    });
    const list = responseModel.data.list;
    modelOptions.value = [];
    if (list.length) {
      modelOptions.value = list;
      memoryOptions.value = list[0].memory.split(',');
      colorOptions.value = list[0].color.split(',');
    }
  }
  document.getElementById('smartAdminLayoutContent').scrollTop = 0;
});

function singleChange(item, e) {
  item.radioSelected = e.target.value;
}

function multipleChange(item, e) {
  console.log(item)
  if (!item.checkedSelected.length) {
    return item.checkedSelected = e;
  }
  const sourceHave0 = item.checkedSelected.findIndex(value => value === '0') !== -1;//原始数据含有0
  const currentHave0 = e.findIndex(value => value === '0') !== -1;//当前数据含有0
  if (sourceHave0 && !currentHave0) {
    item.checkedSelected = [];
    return;
  }
  if (!sourceHave0 && currentHave0) {
    item.checkedSelected = ['0'];
  } else {
    item.checkedSelected = e.filter(value => value !== '0');
  }
}

let modelSearchTime = 0;

async function modelSearch(val) {
  console.log(val)
  clearTimeout(modelSearchTime);
  modelSearchTime = setTimeout(() => {
    modelApi.queryPage({
      modelName: val, //型号名称
      pageNum: 1,
      pageSize: 200,
    }).then(res => {
      modelOptions.value = res.data.list;
    })
    console.log(modelOptions.value)
  }, 200);
}

function modelChange(val, e) {
  formData.modelId = val;
  memoryOptions.value = e.memory.split(',');
  colorOptions.value = e.color.split(',');
  formData.storage = undefined;
  formData.color = undefined;
}

// 模版选项显示添加图片对话框
function showRowDataImg(templateIndex, index) {
  aboutImgDialog.checkDeviceImgs = formData.imgs.map(item => ({url: item.url, checked: false})) || [];
  aboutImgDialog.visible = true;
  aboutImgDialog.templateIndex = templateIndex;
  aboutImgDialog.rowDataIndex = index;
  aboutImgDialog.title = templateList.value[aboutImgDialog.templateIndex]?.children[aboutImgDialog.rowDataIndex]?.subject;
  console.log(templateList.value[aboutImgDialog.templateIndex]?.children[aboutImgDialog.rowDataIndex])
}

// 模版选项删除图片
function removeAboutImg(index) {
  templateList.value[aboutImgDialog.templateIndex]?.children[aboutImgDialog.rowDataIndex]?.imgLists.splice(index, 1)
}

function hideAboutImgDialog() {
  aboutImgDialog.checkDeviceImgs = [];
  aboutImgDialog.uploadedImgs = [];
  aboutImgDialog.visible = false;
  aboutImgDialog.templateIndex = undefined;
  aboutImgDialog.rowDataIndex = undefined;
  aboutImgDialog.title = undefined;
}

function aboutImgDialogSave() {

}

// 模版选项添加图片
function addAboutImg() {
  const imgLength = templateList.value[aboutImgDialog.templateIndex]?.children[aboutImgDialog.rowDataIndex]?.imgLists.length;
  const checkDeviceImgs = aboutImgDialog.checkDeviceImgs.filter(item => item.checked).map(item => item.url);
  console.log(checkDeviceImgs);
  if (checkDeviceImgs.length + aboutImgDialog.uploadedImgs.length === 0) {
    return message.error(`请选择要添加的图片`);
  }
  if (imgLength + checkDeviceImgs.length + aboutImgDialog.uploadedImgs.length > 5) {
    return message.error(`说明图片最多添加五张,当前已有${imgLength}张,还可以添加${5 - imgLength}张,当前选中${+checkDeviceImgs.length + aboutImgDialog.uploadedImgs.length}张`);
  }
  templateList.value[aboutImgDialog.templateIndex]?.children[aboutImgDialog.rowDataIndex]?.imgLists.push(...checkDeviceImgs, ...aboutImgDialog.uploadedImgs.map(item => item.url))
  message.success('图片添加成功');
  aboutImgDialog.checkDeviceImgs = formData.imgs.map(item => ({url: item.url, checked: false})) || [];
  aboutImgDialog.uploadedImgs = [];
  console.log(...checkDeviceImgs, ...aboutImgDialog.uploadedImgs.map(item => item.url))
}

function checkDeviceImgChange(e) {
  console.log(e)
  formData.imgs = e;
  // const imgType = record.icon ? record.icon.split('_') : '';
  // defaultImgList.arr = record.icon ? [{fileUrl: record.icon, fileType: imgType[imgType.length - 1]}] : [];
}

function aboutImgChange(e) {
  console.log(e)
  aboutImgDialog.uploadedImgs = e;
}

function cancel() {
  window.history.back();
  useUserStore().closeTagNav(route.name, false);
}

async function save() {
  if (!formData.status) {
    return message.error('请选择质检状态');
  }
  if (formData.status === 1 && !formData.resultBak.length) {
    return message.error('请选择质检中断原因');
  }
  let modelName = '';
  modelOptions.value.forEach(item => {
    if (item.id === formData.modelId) {
      modelName = item.modelName;
    }
  })

  if (printRequire.value) {
    const index = JSON.parse(localStorage.getItem('deviceInfoPrinter'));
    if (index === null) {
      message.warn('未设置标签打印机，请先设置打印机。')
      return printerRef.showPrinterModal();
    }
  }
  let result = undefined;
  if (deviceId.value) {
    result = await orderApi.updateDevice({
      ...formData,
      noSuchFlag: JSON.stringify(formDataNoneItem),
      modelName,
      orderId: orderId.value,
      imgs: JSON.stringify(formData.imgs),
      resultBak: JSON.stringify(formData.resultBak),
      checkContext: JSON.stringify(templateList.value)
    })
    message.success('修改成功');
  } else {
    result = await orderApi.addDevice({
      ...formData,
      noSuchFlag: JSON.stringify(formDataNoneItem),
      modelName,
      orderId: orderId.value,
      imgs: JSON.stringify(formData.imgs),
      resultBak: JSON.stringify(formData.resultBak),
      checkContext: JSON.stringify(templateList.value)
    })
    message.success('添加成功');
  }
  if (printRequire.value) {
    printerRef.value.printDeviceInfo({
      modelName,
      storage: formData.storage,
      serialNumber: formData.serialNumber,
      machineCode: result.data
    });
  }
  cancel();
  console.log(templateList)
}

function showCheckTemplateModal() {
  checkTemplateRef.value.showModal();
}

function changeBaseNoneItem(valueName, noneItemName) {
  formData[valueName] = undefined;
  formDataNoneItem[noneItemName] = !formDataNoneItem[noneItemName]
}

function storageAreaChange() {
  goodsShelfOptions.value = [];
  if (!formData.storageId) {
    return;
  }
  storageRackApi.queryPage({
    storageId: formData.storageId,
    pageNum: 1,
    pageSize: 200
  }).then(res => {
    goodsShelfOptions.value = res.data.list;
  });
}

function itemNoneItem(rowData) {
  rowData.noneItem = !rowData.noneItem;
  if (rowData.optionType === 1) {
    rowData.radioSelected = '0';
  } else {
    rowData.checkedSelected = ['0']
  }
}

</script>

<style lang="less" scoped>
.row {
  margin-bottom: 18px;
  display: flex;
  flex-direction: row;
  align-items: center;

  .label {
    display: inline-block;
    width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: right;
    margin-right: 8px;
  }

  .rowContent {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
    align-items: center;
  }

  .notExist {
    width: 80px;
    float: right;
  }
}

.infoIcon {
  border: 1.4px solid #40a9ff;
  width: 18px;
  height: 18px;
  border-radius: 10px;
  display: inline-flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  color: #40a9ff;
  font-weight: 600;
  font-size: 12px;
  cursor: pointer;
  margin-right: 24px;
  position: relative;
}

.infoIcon:hover:after {
  content: attr(data-title);
  color: rgba(0, 0, 0, .4);
  width: 200px;
  position: absolute;
  top: 18px;
  right: -204px;
  background: white;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, .1);
  opacity: 1;
  z-index: 9999;
  padding: 4px;
}
</style>